// 8. 顶层模块
module top_module(
    input clk,              // 系统时钟
    input rst_n,            // 复位信号
    input start_btn,        // 开始按钮
    input reset_btn,        // 重置按钮
    input [8:0] key_inputs, // 9个数字按键(1-9)
    
    // 4个不带译码器的数码管接口
    output [7:0] a_to_g,    // 7段显示+小数点
    output [3:0] an,        // 数码管选择
    
    // 2个带译码器的数码管接口
    output [3:0] penalty_tens_bcd,  // 惩罚时间十位
    output [3:0] penalty_ones_bcd   // 惩罚时间个位
);

    // 内部信号定义
    wire clk_100ms;
    wire [1:0] game_state;
    wire game_start, game_reset;
    wire [3:0] current_digit, digit_index;
    wire sequence_complete;
    wire input_correct, input_error, digit_advance;
    wire [15:0] total_time_100ms, penalty_time_100ms;
    wire [15:0] display_4digit;
    
    // 模块实例化
    clk_divider u_clk_divider(
        .clk(clk),
        .rst_n(rst_n),
        .clk_100ms(clk_100ms)
    );
    
    game_controller u_game_controller(
        .clk(clk),
        .rst_n(rst_n),
        .start_btn(start_btn),
        .reset_btn(reset_btn),
        .sequence_complete(sequence_complete),
        .game_state(game_state),
        .game_start(game_start),
        .game_reset(game_reset)
    );
    
    digit_sequence u_digit_sequence(
        .clk(clk),
        .rst_n(rst_n),
        .game_start(game_start),
        .game_reset(game_reset),
        .digit_advance(digit_advance),
        .current_digit(current_digit),
        .digit_index(digit_index),
        .sequence_complete(sequence_complete)
    );
    
    game_timer u_game_timer(
        .clk_100ms(clk_100ms),
        .rst_n(rst_n),
        .game_start(game_start),
        .game_reset(game_reset),
        .game_state(game_state),
        .total_time_100ms(total_time_100ms)
    );
    
    input_handler u_input_handler(
        .clk(clk),
        .rst_n(rst_n),
        .key_inputs(key_inputs),
        .current_digit(current_digit),
        .game_state(game_state),
        .input_correct(input_correct),
        .input_error(input_error),
        .digit_advance(digit_advance)
    );
    
    penalty_timer u_penalty_timer(
        .clk(clk),
        .rst_n(rst_n),
        .game_reset(game_reset),
        .input_error(input_error),
        .penalty_time_100ms(penalty_time_100ms)
    );
    
    display_controller u_display_controller(
        .clk(clk),
        .rst_n(rst_n),
        .current_digit(current_digit),
        .total_time_100ms(total_time_100ms),
        .penalty_time_100ms(penalty_time_100ms),
        .game_state(game_state),
        .display_4digit(display_4digit),
        .penalty_tens(penalty_tens_bcd),
        .penalty_ones(penalty_ones_bcd)
    );
    
    // 使用提供的x7seg模块
    x7seg u_x7seg(
        .x(display_4digit),
        .clk(clk),
        .clr_n(rst_n),
        .a_to_g(a_to_g),
        .an(an)
    );
    
endmodule